package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetUserAuthParam(param map[string]interface{}) (*models_main.UserAuth, error) {
	o := &models_main.UserAuth{}
	err := mysql.Condition(mysql.GetRTable(&models_main.UserAuth{}), param, "", "", 0, 0).Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	return o, err
}

func InsertUserAuth(session *gorm.DB, auth *models_main.UserAuth) error {
	fName := "InsertUserAuth"
	if session == nil {
		session = global.GetX()
	}
	err := session.Create(auth).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func DeleteUserAuth(session *gorm.DB, auth *models_main.UserAuth) error {
	fName := "DeleteUserAuth"
	if session == nil {
		session = global.GetX()
	}
	err := session.Where("uid = ?", auth.Uid).Delete(auth).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func GetUserAddress(param map[string]interface{}) (*models_main.UserAddress, error) {
	fName := "GetUserAddress"
	o := &models_main.UserAddress{}
	table := mysql.GetRTable(&models_main.UserAddress{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}
